<template>
  <div class="container">
    <!-- 面包屑导航 -->
    <div class="topNav">
      <el-breadcrumb :separator-icon="ArrowRight">
        <el-breadcrumb-item :to="{ name: 'base' }">仓库系统</el-breadcrumb-item>
        <el-breadcrumb-item>
          <span v-if="code">编辑出库单</span>
          <span v-if="!code">新增出库单</span>
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <div class="together-content">
      <!-- 新增/编辑入库单的入库单信息 -->
      <div>
        <el-form :inline="true" label-width="auto" style="width: 100%">
          <!-- 调拨单编码 -->
          <el-form-item label="单据编号" v-if="outboundOrder.code">
            <el-input v-model="outboundOrder.code" style="width: 150px; height: 1.5rem" readonly
              v-if="outboundOrder.code" />
          </el-form-item>

          <!--客户 -->
          <el-form-item label="客户" v-if="outboundOrder.customerCode">
            <el-input v-model="outboundOrder.customerName" style="width: 150px; height: 1.5rem" readonly
              v-if="outboundOrder.customerCode" />
          </el-form-item>

          <!-- 时间范围选择 -->
          <el-form-item label="日期">
            <el-date-picker v-model="outboundOrder.createdTime" type="datetime" placeholder="选择日期" size="small"
              format="YYYY/MM/DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" style="width: 150px" />
          </el-form-item>

          <!-- 不需要，关联采购单后有供应商信息  -->
          <!-- <el-form-item label="供应商">
            <el-select style="width: 150px">
              <el-option />
            </el-select>
          </el-form-item> -->

          <!-- 业务类别 -->
          <el-form-item label="业务">
            <el-select style="width: 200px" v-model="outboundOrder.type">
              <el-option label="请选择" value="" />
              <el-option label="销售出库" :value="1" />
              <el-option label="采购退货" :value="2" />
              <el-option label="调拨出库" :value="3" />
              <el-option label="盘亏出库" :value="4" />
              <el-option label="其他出库" :value="0" />
            </el-select>
          </el-form-item>

          <!--  -->
          <el-form-item label="关联源单">
            <el-input style="width: 150px" placeholder="选择源单" readonly />
          </el-form-item>
        </el-form>
      </div>

      <!-- 分割线 -->
      <el-divider />

      <!-- 操作按钮 -->
      <div style="margin-bottom: 15px; text-align: right">
        <el-button type="primary" size="small" @click="save">保存</el-button>
        <el-button type="success" size="small" @click="saveAndSubmit">保存并提交</el-button>
        <el-button type="info" size="small" @click="auditor">审核</el-button>
        <el-button type="info" size="small">反审核</el-button>
      </div>

      <!-- 表格 -->
      <el-table :data="outboundDetailList" style="width: 100%" border>
        <!-- 操作列 -->
        <el-table-column label="操作" width="80px" align="center" fixed="left">
          <template #default="scope">
            <!-- add -->
            <el-button link type="success" size="small" plain @click="addDetailRow(scope.$index)"><el-icon>
                <Plus />
              </el-icon></el-button>
            <!-- del -->
            <el-button link type="danger" size="small" plain @click="removeDetailRow(scope.$index)"><el-icon>
                <Minus />
              </el-icon></el-button>
          </template>
        </el-table-column>

        <!-- 商品 -->
        <el-table-column label="商品" width="180" align="center">
          <template #default="scope">
            <el-input :value="scope.row.goodsCode ? scope.row.goodsCode + '' + scope.row.goodsName : ''" size="small"
              style="width: 95%" placeholder="选择商品" @click="openGoodsDialog(scope.row, scope.$index)" readonly />
          </template>
        </el-table-column>

        <!-- 商品类别 -->
        <el-table-column label="商品类别" width="150px" align="center">
          <template #default="scope">
            <el-input v-model="scope.row.category" size="small" style="width: 95%" placeholder="商品类别" readonly />
          </template>
        </el-table-column>

        <!-- 规格 -->
        <el-table-column label="规格" width="150px" align="center">
          <template #default="scope">
            <el-input v-model="scope.row.specification" size="small" style="width: 95%" placeholder="规格" readonly />
          </template>
        </el-table-column>

        <!-- 采购单位 -->
        <el-table-column label="单位" width="120" align="center">
          <template #default="scope">
            <el-select v-model="scope.row.unit" size="small" style="width: 95%" :disabled="!scope.row.goodsCode" />
          </template>
        </el-table-column>

        <!-- 仓库 -->
        <el-table-column label="仓库" width="190px" align="center">
          <template #default="scope">
            <el-input v-model="scope.row.warehouseName" readonly placeholder="(所有)"
              @click="openWarehouseDialog(scope.row)" style="width: 95%" size="small" />
          </template>
        </el-table-column>

        <!-- 可用库存 -->
        <el-table-column label="可用库存" width="150px" align="center">
          <template #default="scope">
            <el-input v-model="scope.row.availableStock" size="small" style="width: 95%" placeholder="可用库存" readonly />
          </template>
        </el-table-column>

        <!-- 批次号（仅当 manageType === 1 时启用） -->
        <el-table-column v-if="showBatch" prop="batchNo" label="批次号" width="180" align="center">
          <template #default="scope">
            <el-input v-model="scope.row.batchNo" size="small" @click="openBatchDialog(scope.row, scope.$index)"
              style="width: 95%" />
          </template>
        </el-table-column>

        <!-- 生产日期（仅当 manageType === 1 时启用） -->
        <el-table-column v-if="showBatch" prop="birthday" label="生产日期" width="180" align="center">
          <template #default="scope">
            <el-input v-model.number="scope.row.birthday" size="small" :disabled="scope.row.manageType == true"
              style="width: 95%" />
          </template>
        </el-table-column>

        <!-- 有效期（仅当 manageType === 1 时启用） -->
        <el-table-column v-if="showBatch" prop="expiration" label="有效期(天)" width="110" align="center">
          <template #default="scope">
            <el-input v-model.number="scope.row.expiration" size="small" :disabled="scope.row.manageType == true"
              style="width: 95%" />
          </template>
        </el-table-column>

        <!-- 入库数量 -->
        <el-table-column prop="quantity" label="数量" width="150" align="center">
          <template #default="scope">
            <el-input-number v-model.number="scope.row.quantity" :step="1" size="small" style="width: 95%" :min="1"
              :max="100000000" @input="scope.row.totalPrice = scope.row.unitPrice * scope.row.quantity" />
          </template>
        </el-table-column>



        <!-- 入库单价 -->
        <el-table-column prop="unitPrice" label="入库单价" width="120" align="center">
          <template #default="scope">
            <el-input type="number" v-model.number="scope.row.unitPrice" size="small" style="width: 95%"
              @input="scope.row.totalPrice = scope.row.unitPrice * scope.row.quantity" />
          </template>
        </el-table-column>

        <!-- 入库金额（自动计算） -->
        <el-table-column prop="totalPrice" label="入库金额" width="120" align="center">
          <template #default="scope">
            <el-input v-model.number="scope.row.totalPrice" readonly size="small" style="width: 95%" />
          </template>
        </el-table-column>

        <!-- 库位 组件还未完善 -->
        <el-table-column prop="warehouseLocationCode" label="库位" width="180" align="center">
          <template #default="scope">
            <el-input readonly size="small" style="width: 95%" @click="openWarehouseLocationDialog(scope.row)" />
          </template>
        </el-table-column>

      </el-table><br />

      <!-- 调拨单备注 -->
      <el-input v-model="outboundOrder.remark" style="width: 100%" type="textarea" placeholder="暂无备注信息" />

      <!--操作日志-->
      <div style="margin-bottom: 15px; text-align: right">
        <br />
        <el-button plain @click="router.push({ name: 'outbound' })">历史记录</el-button>
        <el-button plain>操作日志</el-button>
      </div>

      <!-- 商品搜索列表弹出对话框 -->
      <el-dialog v-model="goodsVisible" title="商品搜索列表" width="60%" style="height: auto;" draggable :show-close="true">
        <!-- 调用商品的搜索组件 -->
        <FreeGoodsSelect v-model="goodsVisible" @confirm="onGoodsSelected"></FreeGoodsSelect>
        <br /><br />
      </el-dialog>

      <!-- 批次号搜索列表弹出对话框 -->
      <el-dialog v-model="batchVisible" width="60%" style="height: auto;" draggable :show-close="true">
        <!-- 调用商品的搜索组件 -->
        <BatchListSelect v-model="batchVisible" @confirm="onBatchSelected" :goodsName="currentRow.goodsName"></BatchListSelect>
        <br /><br />
      </el-dialog>

      <!-- 仓库搜索列表弹出对话框 -->
      <el-dialog v-model="warehouseVisible" title="仓库搜索列表" width="60%" style="height: auto;" draggable
        :show-close="true">
        <!-- 调用仓库的搜索组件 -->
        <WareHouse ref="warehouseRef"
          :info="{ selection: true, no: false, name: true, code: true, status: false, op: false, outButton: true }" />
        <br /><br />
      </el-dialog>

    </div>
  </div>
</template>

<script setup>
import { ref, defineProps, watch, onMounted, inject } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from 'element-plus'
import FreeGoodsSelect from "@/util/FreeGoodsSelect.vue";
import WareHouse from '@/views/basic/WareHouse.vue'
import BatchListSelect from "./BatchListSelect.vue";
let router = useRouter();
let axios = inject("axios");
let outboundOrder = ref({
  createdTime: formatDate(new Date()),
  type: '',
  sourceOrderCode: ''
});

// 商品搜索对话框展示
let goodsVisible = ref(false)
//当前选中行
let currentRow = ref(null), currentIndex = ref(null);
//是否需要展示批次相关信息
let showBatch = ref(false);
let outboundDetailList = ref([]);

function formatDate(date) {
  const pad = n => n.toString().padStart(2, '0')
  const d = new Date(date)
  return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`
}

//仓库搜索选中结果
let warehouseVisible = ref(false)
let warehouseRef = ref();
watch(warehouseVisible, (newVisible) => {
  if (!newVisible) {
    if (warehouseRef.value && warehouseRef.value.selectedArray.length > 0) { //这里需要加上if判断，子组件中没有选择数据时为undefined，可能用于点击仓库，但是没选择，所以导致undefined报错
      currentRow.value.warehouseName = warehouseRef.value.selectedArray[0].name //只选择一个，默认第一个
      currentRow.value.warehouseCode = warehouseRef.value.selectedArray[0].code //只选择一个，默认第一个
      //获取到仓库编码，存数据库用，仓库name仅用作展示
      //用完之后清空，避免污染其他地方数据
      warehouseRef.value.clearSelected();
    }
  }
})

let batchVisible = ref(false);
let treeData = ref([]);

const props = defineProps(["id"]);

function openWarehouseDialog(row) {
  warehouseVisible.value = true,
    currentRow.value = row;
}


function openWarehouseLocationDialog(row) {
  if (!row.warehouseName) {
    ElMessage({ message: '请先选择仓库！', type: 'warning', })
    return;
  }
  row.warehouseLocationCode = "KW_TEST"
  row.warehouseLocationName = "测试库位"
  currentRow.value = row;
}

function openGoodsDialog(row, index) {
  goodsVisible.value = true;
  currentRow.value = row;
  currentIndex.value = index;
  console.log("当前选中行：", row)
}

function openBatchDialog(row, index) {
  batchVisible.value = true;
  currentRow.value = row;
  currentIndex.value = index;
  console.log("当前选中行：", row)
}

//这里的selected就是选中的商品列表，可以通过自行处理这些数据
const onGoodsSelected = (selected) => {
  if (selected.length > 0) {
    //当前行后面添加选中的的商品信息
    let arr = [];
    for (let i = 0; i < selected.length; i++) {
      if (selected[i].type == 1) {
        showBatch.value = true; //此处应该是每次数组变化，就需要进行判断，改成watch -------------------------------未改------------------------------
      }
      let obj = {
        goodsCode: selected[i].code,
        goodsName: selected[i].code + ' ' + selected[i].name,
        unit: selected[i].unit,
        category: selected[i].category,
        availableStock: selected[i].availableStock,
        specification: selected[i].specification,
        warehouseCode: selected[i].warehouseCode,
        warehouseName: selected[i].warehouseName,
        batchNo: selected[i].type == 1 ? selected[i].batchNo : null,
        birthday: selected[i].type == 1 ? selected[i].birthday : null,
        expiration: selected[i].type == 1 ? selected[i].expiration : null,
        type: selected[i].managerType,
        quantity: 1, //默认
        unitPrice: 0.0,
        totalPrice: 0.0,
      }
      arr[i] = obj
    }
    console.log("arr", arr);
    //当前下标往后添加选中的商品
    outboundDetailList.value.splice(currentIndex.value, 1, ...arr);
    console.log("onGoodsSelected", selected)
  }
}

//这例的selected就是选中的批次列表
const onBatchSelected = (selected) => {
  if (selected.length > 0) {
    let arr = []
    for (let i = 0; i < selected.length; i++) {
      let obj = JSON.parse(JSON.stringify(currentRow.value)); //深拷贝
      obj.batchNo = selected[i].code;
      arr.push(obj);
    }
    //这里是参考精斗云中的效果，选中多个批次，则复制几份对象
    outboundDetailList.value.splice(currentIndex.value, 1, ...arr);
  }
}
const addDetailRow = (index) => {
  outboundDetailList.value.splice(index + 1, 0, {});
}
const removeDetailRow = (index) => {
  if (outboundDetailList.value.length === 1) {
    ElMessage({
      message: '至少保留一条记录',
      type: 'warning',
    })
    return;
  }
  outboundDetailList.value.splice(index, 1);
}

//  原始明细（用于修改时候的和原数据对比）
const originalOrder = ref(null), originalDetailList = ref([]);

const save = () => {
  //根据code判断此处是修改还是新增
  if (props.id || outboundOrder.value.id) {
    //修改 - 对比原数组。分别获得 新增、修改、删除三个数组。
    //1.map根据id快速获取原数组
    const originalMap = new Map(
      originalDetailList.value.map(item => [item.id, item])
    );
    //2.遍历当前列表：找新增 & 修改
    let addArr = [], delArr = [], modArr = [];
    outboundDetailList.value.forEach(i => {
      if (!i.id) {
        //合理校验

        addArr.push(i); //新增
      } else {
        //判断修改
        if (hasModifiedDetail(i, originalMap.get(parseInt(i.id)))) {
          modArr.push(i);
        }
        //map数据比较过就删除， map中数据 - 当前明细 = 已删除数据
        originalMap.delete(i.id);
      }
    })
    //3.剩下的 originalMap 中的 id 就是被删除的
    for (const id of originalMap.keys()) {
      delArr.push(id);
    }
    //提交修改
    axios({
      url: `/xyy/outbound/modify`,
      method: 'post',
      data: {
        orderModified: hasModifiedOrder(originalOrder.value, outboundOrder.value),
        addArr: addArr,
        modArr: modArr,
        delArr: delArr,
        outboundOrder: outboundOrder.value
      }
    }).then(rs => {
      if (rs.data.code == 5200) {
        ElMessage({ message: "修改入库单成功", type: 'success', });
        router.push({ name: 'outbound' });
      }
    })
  }
  else {//新增
    // 过滤掉 goods 为空的明细项
    const filteredDetailList = outboundDetailList.value.filter(item => {
      // 检查 goods 是否不为空
      return item.goodsCode && item.goodsName;
    });
    //校验数据是否合理
    let hasZeroUnitPrice = false;
    //1、校验出库单：类型不能为空
    if (outboundOrder.value.type == '') { ElMessage({ message: '请选择入库单类型', type: 'warning', }); return; }
    //2、校验出库明细
    if (!filteredDetailList || filteredDetailList.length == 0) { ElMessage({ message: '请添加入库明细', type: 'warning', }); return; }
    for (let i = 0; i < filteredDetailList.length; i++) {
      let detail = filteredDetailList[i];
      //检查单价
      if (detail.unitPrice <= 0) hasZeroUnitPrice = true;
      if (!detail.warehouseCode || !detail.warehouseName) { ElMessage({ message: `请选择【${detail.goodsName}】的仓库`, type: 'warning', }); return; }
      if (detail.quantity <= 0) { ElMessage({ message: `商品【${detail.goodsName}】的数量不能为空`, type: 'warning', }); return; }
      if (detail.type && detail.type == 1 && !detail.batchNo) { ElMessage({ message: `商品【${detail.goodsName}】的批次号不能为空`, type: 'warning', }); return; }
      if (!detail.warehouseLocationCode || !detail.warehouseLocationName) { ElMessage({ message: `请选择【${detail.goodsName}】的库位`, type: 'warning', }); return; }
    }
    if (hasZeroUnitPrice) {
      ElMessageBox.confirm(
        '存在入库单价为0的商品,是否仍要继续?',
        '警告',
        {
          confirmButtonText: '继续',
          cancelButtonText: '取消',
          type: 'warning',
          center: true,
        }
      )
        .then(() => {
          add(filteredDetailList);
        })
        .catch(() => {
          console.log("用户取消保存");
        })
    } else {
      add(filteredDetailList);
    }

  }
}

const saveAndSubmit = () => {
  //提交
  outboundOrder.value.status = 2;
  save();
}

//判断当前 出库明细 是否修改
function hasModifiedDetail(current, original) { //判断这个商品是否修改的前提：商品id或code存在，其他：商品单位、仓库、批次号、库位、数量、单价修改即表示该明细修改了
  const fields = ["unit", "warehouseCode", "batchNo", "warehouseLocationCode", "quantity", "unitPrice"];
  return fields.some(field => current[field] != original[field]);
}
//判断当前 出库单 是否修改
function hasModifiedOrder(current, original) {
  const fields = ["createdTime", "type", "sourceOrderCode", "remark", "status"]
  return fields.some(field => current[field] != original[field]);
}

// 新增出库和明细方法
const add = (filteredDetailList) => {
  axios({
    url: '/xyy/outbound/create',
    method: 'post',
    data: {
      outboundOrder: outboundOrder.value,
      // 过滤后的明细列表
      outboundOrderItemList: filteredDetailList
    }
  }).then(rs => {
    console.log(rs);
      if (rs.data.code == 5200) {
        ElMessage({ message: "新增入库单成功", type: 'success', });
        router.push({ name: 'outbound' });
      } else {
        ElMessage({ message: "新增入库单失败", type: 'danger', });
      }
  })
}

// 审核 - 根据入库表id进行审核
const auditor = () => {
  axios({
    url: `/xyy/outbound/auditor`,
    method: 'post',
    data: {
      outboundOrder: outboundOrder.value,
      outboundOrderItemList: outboundDetailList.value,
    }
  }).then(rs => {
    if (rs.data.code == 5200) {
      ElMessage({ message: "审核成功", type: 'success', });
      router.push({ name: 'outbound' })
      return;
    }
    ElMessage({ message: "审核失败", type: 'danger', });
  })
}

//进入修改操作的数据初始化
function init() {
  axios({
    url: '/xyy/outbound/get/' + props.id,
    method: 'post',
  }).then(rs => {
    console.log(rs);
    if (rs.data.code == 5200 && rs.data.outboundOrderRequest) {
      outboundOrder.value = rs.data.outboundOrderRequest.outboundOrder;
      outboundDetailList.value = rs.data.outboundOrderRequest.outboundOrderItemList;
      outboundDetailList.value.forEach(i => {
        if (i.type == 1) {
          showBatch.value = true;
        }
      })
      //深拷贝一份初始数据，方便后面操作
      originalDetailList.value = JSON.parse(JSON.stringify(outboundDetailList.value));
      originalOrder.value = JSON.parse(JSON.stringify(outboundOrder.value));
    }
  })
}

onMounted(() => {
  //初始化加载该公司所有仓库信息，后续根据查询条件进行动态筛选 --------------------------------未完成--------------------------------
  treeData.value = [
    {
      code: 'KW001',
      name: 'A1',
      children: [
        {
          code: 'KW002',
          name: 'A1-01',
          children: [
            { code: 'KW003', name: 'A1-01-01' }
          ]
        }
      ]
    },
    {
      code: 'KW004',
      name: 'B1',
      children: []
    }
  ];
  //如果是修改，获取到入库单和入库明细
  if (props.id) {
    init();
  } else {
    outboundDetailList.value = [{}, {}, {}, {}, {}]
  }
})


</script>

<style></style>